package com.acane.instagram.feature.chat

import android.util.Log
import com.acane.instagram.core.config.NotificationManager
import com.acane.instagram.core.model.Notification
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener

class ChatWebSocketClient(private val listener: Listener) {
    private val client = OkHttpClient()
    lateinit var webSocket: WebSocket
    private val gson = Gson()

    interface Listener {
        fun onMessageReceived(message: Notification)
        fun onConnected()
        fun onClosed(code: Int, reason: String)
        fun onFailure(t: Throwable, response: Response?)
    }

    fun connect(url: String, sessionId: String) {
        val request = Request.Builder()
            .url(url) // 替换为您的WebSocket服务器地址，例如：ws://your-backend-server-url/chat
            .addHeader("Cookie", "JSESSIONID=$sessionId") // 使用sessionId
            .build()

        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                super.onOpen(webSocket, response)
                // WebSocket连接成功
                Log.d("ChatWebSocketClient", "WebSocket连接成功")
                listener.onConnected()
            }

            // ChatWebSocketClient.kt
            override fun onMessage(webSocket: WebSocket, text: String) {
                try {
                    Log.d("WebSocket", "接收到消息: $text")
                    val notification = NotificationManager.parseMessageWrapper(text)

                    listener.onMessageReceived(notification)
                } catch (e: Exception) {
                    Log.e("WebSocket", "解析失败: ${e.message}")
                }
            }

            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosing(webSocket, code, reason)
                // WebSocket关闭
                Log.d("ChatWebSocketClient", "WebSocket关闭: $code, $reason")
                listener.onClosed(code, reason)
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                super.onFailure(webSocket, t, response)
                // WebSocket连接失败
                Log.d("ChatWebSocketClient", "WebSocket连接失败: ${t.message}")
                listener.onFailure(t, response)
            }
        })

        client.dispatcher.executorService.shutdown()
    }

    fun close() {
        if (::webSocket.isInitialized) {
            webSocket.close(1000, null)
        }
    }
}
